package aufgabenserie_1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class SkyTale {
	
	public static void main(String[] vargs){
		skyTale_crypt(new File("plaintextSkytale.txt"), new File ("skytale_out"), true, 4 );
		System.out.println("-----------------");
		skyTale_crypt(new File("skytale_out"), new File ("skytale_out_plaintext"), false, 4 );
	}
	
	public static void skyTale_crypt(File input, File output, boolean encrypt, int charsPerRound ){
		try {
			
			if(encrypt){
				FileReader fr = new FileReader(input);
				int i = 0;
				while(fr.ready()) {
					fr.read();
					i++;
				}
				fr.close();
				fr = new FileReader(input);
				
				int numLines = (i+ (charsPerRound-1) ) / charsPerRound;
				System.out.println(i + " " + numLines);
				
				char[][] matrix = new char[numLines][charsPerRound];
				
				for (int j = 0; j < matrix[0].length; j++) {
					for (int j2 = 0; j2 < matrix.length; j2++) {
						if(fr.ready()){
							matrix[j2][j] = (char) fr.read();
							System.out.print(matrix[j2][j]);
						}else{
							matrix[j2][j] = ' ';
							System.out.print(matrix[j2][j]);
						}
					}
					System.out.println();
				}			
				fr.close();
				
				FileWriter fw = new FileWriter(output);
				for (int j = 0; j < matrix.length; j++) {
					for (int j2 = 0; j2 < matrix[0].length; j2++) {
						System.out.print( matrix[j][j2] );
						fw.append(matrix[j][j2] );
					}
				}	
				System.out.println();
				fw.close();
				
			}else{				
				FileReader fr = new FileReader(input);
				int i = 0;
				while(fr.ready()) {
					fr.read();
					i++;
				}
				fr.close();
				fr = new FileReader(input);
				
				int numLines = (i+2) / charsPerRound;
				System.out.println(numLines);
				
				char[][] matrix = new char[numLines][charsPerRound];
				
				for (int j = 0; j < matrix.length; j++) {
					for (int j2 = 0; j2 < matrix[0].length; j2++) {
						if(fr.ready()){
							matrix[j][j2] = (char) fr.read();
						}
					}
				}			
				fr.close();
				
				FileWriter fw = new FileWriter(output);
				for (int j = 0; j < matrix[0].length; j++) {
					for (int j2 = 0; j2 < matrix.length; j2++) {
						System.out.print( matrix[j2][j] );
						fw.append(matrix[j2][j] );
					}
					System.out.println();
				}											
				fw.close();
				
			}
			
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
